package com.mysoft.gfyx.clue.controller;

import com.mysoft.framework.common.exception.BusinessLogicException;
import com.mysoft.framework.common.util.MappingUtil;
import com.mysoft.framework.modeling.dto.ListDataResult;
import com.mysoft.framework.modeling.dto.LoadDataParams;
import com.mysoft.framework.modeling.dto.OptionItem;
import com.mysoft.framework.mvc.api.Controller;
import com.mysoft.framework.rpc.annotation.PubAction;
import com.mysoft.framework.rpc.annotation.PubService;
import com.mysoft.framework.rpc.contants.RequestPrefix;
import com.mysoft.framework.sdk.system.dto.UserDTO;
import com.mysoft.gfyx.clue.controller.dto.*;
import com.mysoft.gfyx.clue.controller.dto.Perm.GetUserAreaPermissionResponseDto;
import com.mysoft.gfyx.clue.dao.dto.ClueFollowRecordsDto;
import com.mysoft.gfyx.clue.dao.entity.Clue;
import com.mysoft.gfyx.clue.dao.entity.Cluefollowprojectinfo;
import com.mysoft.gfyx.clue.mip.BigDataDeveloperService;
import com.mysoft.gfyx.clue.mip.dto.ImportDeveloperRequestDto;
import com.mysoft.gfyx.clue.mip.dto.ImportDeveloperResponseDto;
import com.mysoft.gfyx.clue.remoteservice.RemoteSystemService;
import com.mysoft.gfyx.clue.remoteservice.dto.SystemGetUserRequestDto;
import com.mysoft.gfyx.clue.service.*;
import com.mysoft.gfyx.clue.service.dto.*;
import com.mysoft.gfyx.common.rpc.opptyservice.OpptyServiceClientFactoryService;
import com.mysoft.gfyx.common.rpc.opptyservice.OpptyServiceClientService;
import com.mysoft.gfyx.common.rpc.opptyservice.dto.GetBuAndUserRequestDto;
import com.mysoft.gfyx.common.util.PermUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;

@PubService(value = "/cluePub", prefix = RequestPrefix.PUB)
public class CluePubController extends Controller {
    @Autowired
    private ClueService clueService;

    @Autowired
    private DataPermissionService dataPermissionService;

    @Autowired
    private CluefollowrecordService cluefollowrecordService;

    @Autowired
    private CluecontacterService cluecontacterService;

    @Autowired
    private PermUtil permUtil;

    @Autowired
    private BigDataDeveloperService bigDataDeveloperService;

    @Autowired
    private RemoteSystemService remoteSystemService;

    @Autowired
    private ProfitProvinceService profitProvinceService;

    @Autowired
    private AreaOptionService areaOptionService;

    @PubAction(value = "/countClue")
    public int countClue(@RequestBody GetCreditDataDto req) {
        return clueService.countDeveloperClue(req.getCreditCode());
    }

    @PubAction(value = "/isAdded")
    public Set<String> isAdded(@RequestBody List<String> req) {
        return clueService.isAdded(req);
    }

    @PubAction(value = "/addClue")
    public boolean addClue(@RequestBody AddClueRequestDto request) {
        // check is permission
        boolean enableCluePerm = permUtil.checkBusinessUnit(permUtil.clueActionCode);
        if (!enableCluePerm) {
            throw new BusinessLogicException("当前操作没有权限，需要操作请购买【线索雷达】模块");
        }
        if (request.getClueGUID() != null && !request.getClueGUID().toString().equals("")) {//update
            ClueDto clueDto = MappingUtil.getSimpleMapperFacade().map(request, ClueDto.class);
            return clueService.updateById(clueDto, request.getClueGUID());
        } else {//add操作
            clueService.checkAndAddClue(request);
            return true;
        }
    }

    @PubAction(value = "/followClue")
    public FollowClueResponseDto followClue(@RequestBody AddClueRequestDto request) {
        // check is permission
        boolean enableCluePerm = permUtil.checkBusinessUnit(permUtil.clueActionCode);
        if (!enableCluePerm) {
            throw new BusinessLogicException("当前操作没有权限，需要操作请购买【线索雷达】模块");
        }

        FollowClueResponseDto followClueResponseDto = new FollowClueResponseDto();
        if (request.getClueGUID() != null && !request.getClueGUID().toString().equals("")) {//update
            ClueDto clueDto = MappingUtil.getSimpleMapperFacade().map(request, ClueDto.class);
            clueService.updateById(clueDto, request.getClueGUID());
        } else {//add操作
            Clue clue = clueService.checkAndAddClue(request);
            followClueResponseDto.setNewClue(clue.isNewAddition());

            ClueFollowRecordDto clueFollowRecordDto = new ClueFollowRecordDto();
            clueFollowRecordDto.setClueGUID(clue.getClueGUID());
            ClueContacterDto clueContacterDto = cluecontacterService.getClueContacterByClueTel(clue.getClueGUID(), request.getContacterTel());
            clueFollowRecordDto.setContacterGUID(clueContacterDto.getClueContacterGUID());
            clueFollowRecordDto.setContactWay(request.getFollowType());
            clueFollowRecordDto.setFollowRecord(request.getFollowContent());
            clueFollowRecordDto.setContactWayStatus(request.getFollowStatus());
            clueFollowRecordDto.setFrom_device(request.getFrom_device());
            cluefollowrecordService.addClueFollowRecord(clueFollowRecordDto);
        }

        return followClueResponseDto;
    }

    @PubAction(value = "/getClueSourceFollowRecords", method = RequestMethod.POST)
    public GetClueFollowRecordsResponseDto getClueSourceFollowRecords(@RequestBody GetClueSourceFollowRecordsRequestDto dto) {
        ClueDto clueDto = clueService.getClueBySource(dto);

        GetClueFollowRecordsResponseDto response = new GetClueFollowRecordsResponseDto();
        List<ClueFollowRecordsDto> list = cluefollowrecordService.getClueFollowRecordsByClueId(clueDto.getClueGUID());

        response.setList(list);
        return response;
    }

    @PubAction(value = "/myClue")
    public ListDataResult myClue(@RequestBody LoadDataParams params) {
        return clueService.myClue(params);
    }

    @PubAction(value = "/regionClue")
    public ListDataResult regionClue(@RequestBody LoadDataParams params) {
        return clueService.regionClue(params);
    }

    @PubAction(value = "/clueDetail")
    public ClueDto clueDetail(@RequestBody GetClueFollowRecordsRequestDto dto) {
        return clueService.clueDetail(UUID.fromString(dto.getClueId()));
    }

    @PubAction(value = "/deleteClue")
    public Boolean deleteClue(@RequestBody GetClueFollowRecordsRequestDto dto) {
        return clueService.deleteClue(UUID.fromString(dto.getClueId()));
    }

    @PubAction(value = "/getClueFollowRecords", method = RequestMethod.POST)
    public GetClueFollowRecordsResponseDto getClueFollowRecords(@RequestBody GetClueFollowRecordsRequestDto dto) {
        UUID clueId = UUID.fromString(dto.getClueId());
        GetClueFollowRecordsResponseDto response = new GetClueFollowRecordsResponseDto();
        List<ClueFollowRecordsDto> list = cluefollowrecordService.getClueFollowRecordsByClueId(clueId);
        response.setList(list);
        return response;
    }

    @PubAction(value = "/addClueFollowRecord", method = RequestMethod.POST)
    @Transactional
    public boolean addClueFollowRecord(@RequestBody AddClueFollowRecordRequestDto dto) {
        // 添加跟进记录
        ClueFollowRecordDto clueFollowRecordDto = MappingUtil.getSimpleMapperFacade().map(dto, ClueFollowRecordDto.class);
        cluefollowrecordService.addClueFollowRecord(clueFollowRecordDto);

        // 更改线索状态
        clueService.changeCooperationStatus(dto.getClueStatus(), dto.getClueGUID());
        return true;
    }

    @PubAction(value = "/getContactors", method = RequestMethod.POST)
    public List<ClueContacterDto> getContactors(@RequestBody GetClueFollowRecordsRequestDto dto) {
        UUID clueId = UUID.fromString(dto.getClueId());
        List<ClueContacterDto> list = cluecontacterService.getClueContactersByClueId(clueId);

        return list;
    }

    @PubAction(value = "/addClueContactor", method = RequestMethod.POST)
    public boolean addClueContactor(@RequestBody ClueContacterDto dto) {
        if (dto.getClueContacterGUID() == null) {
            cluecontacterService.addClueContactor(dto);//新增
        } else {
            cluecontacterService.updateClueContactor(dto);//修改
        }

        return true;
    }

    @PubAction(value = "/deleteClueContactor", method = RequestMethod.POST)
    public boolean deleteClueContactor(@RequestBody DeleteByIdRequestDto dto) {
        cluecontacterService.deleteClueContactor(dto);
        return true;
    }

    @PubAction(value = "/clueContactorDetail")
    public ClueContacterDto clueContactorDetail(@RequestBody GetByIdRequestDto dto) {
        return cluecontacterService.getClueContactersById(UUID.fromString(dto.getId()));
    }

    @PubAction(value = "/getClueProjects", method = RequestMethod.POST)
    public List<Cluefollowprojectinfo> getClueProjects(@RequestBody GetClueFollowRecordsRequestDto dto) {
        UUID clueId = UUID.fromString(dto.getClueId());
        return clueService.getClueProjects(clueId);
    }

    @PubAction(value = "/addClueProject", method = RequestMethod.POST)
    public boolean addClueProject(@RequestBody Cluefollowprojectinfo dto) {
        if (dto.getClueFollowProjectInfoGUID() == null) {
            clueService.addClueProject(dto);//新增
        } else {
            clueService.updateClueProject(dto);//修改
        }

        return true;
    }

    @PubAction(value = "/deleteClueProject", method = RequestMethod.POST)
    public boolean deleteClueProject(@RequestBody DeleteByIdRequestDto dto) {
        clueService.deleteClueProject(dto);
        return true;
    }

    @PubAction(value = "/clueProjectDetail", method = RequestMethod.POST)
    public ClueFollowProjectInfoDto clueProjectDetail(@RequestBody GetByIdRequestDto dto) {
        return clueService.getClueProjectById(UUID.fromString(dto.getId()));
    }

    @PubAction(value = "/searchCompanyQuery", method = RequestMethod.POST)
    public List<OptionItem> searchCompanyQuery(@RequestBody SearchCompanyQueryRequestDto dto) {
        List<OptionItem> res = clueService.searchCompanyQuery(dto);
        return res;
    }

    @PubAction(value = "/getMainDataAndFeeding", method = RequestMethod.POST)
    public CustomerMainDataDto getMainDataAndFeeding(@RequestBody GetCompanyNameDto getCompanyNameDto) {
        ImportDeveloperRequestDto dto = new ImportDeveloperRequestDto();
        CustomerMainDataDto customerMainDataDto = new CustomerMainDataDto();
        ImportDeveloperResponseDto importDeveloperResponseDto = bigDataDeveloperService.importDeveloper(getCompanyNameDto.getCompanyName());
        if (importDeveloperResponseDto != null && importDeveloperResponseDto.getData() != null) {
            customerMainDataDto.setProvinceCode(importDeveloperResponseDto.getData().getProvince_code());
            customerMainDataDto.setProvinceName(importDeveloperResponseDto.getData().getProvince_name());
            customerMainDataDto.setAreaCategoryCode(importDeveloperResponseDto.getData().getCity_code());
            customerMainDataDto.setAreaCategoryName(importDeveloperResponseDto.getData().getCity_name());
            customerMainDataDto.setCreditCode(importDeveloperResponseDto.getData().getCredit_code());
        }
        return customerMainDataDto;
    }

    @PubAction(value = "/getAllUsers", method = RequestMethod.POST)
    public List<UserDTO> getAllUsers(@RequestBody(required = false) SystemGetUserRequestDto dto) {
        List<UserDTO> res = remoteSystemService.GetAllUsers(dto);
        return res;
    }

    @PubAction(value = "/getProfitProvinceList", method = RequestMethod.POST)
    public List<OptionItem> getProfitProvinceList() {
        List<OptionItem> profitProvinceList = profitProvinceService.getProfitProvinceList();

        GetUserAreaPermissionResponseDto userAreaPermissionDto = dataPermissionService.getUserPermissionArea();

        //如果用户拥有全国权限或者是没有设置地区权限,就取权益地区返回
        if (userAreaPermissionDto == null
                || userAreaPermissionDto.getArea() == null
                || userAreaPermissionDto.getArea().contains("0")
                || userAreaPermissionDto.getArea().size() == 0) {
            return profitProvinceList;
        }

        List<OptionItem> result = new ArrayList<>();
        profitProvinceList.forEach(p -> {
            if (userAreaPermissionDto.getArea().contains(p.getValue())) {
                //取权益和权限的交集
                result.add(p);
            }
        });

        return result;
    }

    @PubAction(value = "/getProfitProvinceAndCity", method = RequestMethod.POST)
    public List<OptionItem> getProfitProvinceAndCity() {
        return areaOptionService.getProfitWithPermissionAreaData();
    }
}
